package packing;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;


/**
 * This is a storage class for a given exam.
 * 
 * This class will retrieve the information about an exam and store it for later
 * use. Functions are provided for easy access to specific information. It will
 * not handle exceptions leaving it up to the calling function.
 */
public class Exam implements Iterator<Question>
{
	int examID, previousQuestion = -1;
	java.sql.Date date_scheduled, date_created;
	ArrayList<Question> questions = new ArrayList<Question>();
	SimpleDateFormat dateFormat = new SimpleDateFormat("MMMMyyyy");

	/**
	 * Creates a new exam with the given id and database connection.
	 * 
	 * @param conn
	 *            Connection to the database.
	 * @param id
	 *            ID of the exam to be stored.
	 */
	public Exam(Connection conn, int id) throws SQLException
	{
		examID = id;

		PreparedStatement pstmt = conn
				.prepareStatement("SELECT question_id, q_version FROM EXAM_QUESTION WHERE exam_id=?");
		pstmt.setInt(1, examID);
		ResultSet rset = pstmt.executeQuery();

		while (rset.next())
		{
			questions.add(new Question(conn, rset.getInt("question_id"), rset
					.getInt("q_version")));
		}
		pstmt.close();
		rset.close();

		pstmt = conn
				.prepareStatement("SELECT date_scheduled, date_created FROM EXAM WHERE exam_id=?");
		pstmt.setInt(1, examID);
		rset = pstmt.executeQuery();

		rset.next();
		date_scheduled = rset.getDate("date_scheduled");
		date_created = rset.getDate("date_created");
		rset.close();
		pstmt.close();

	}

	/**
	 * Get the number of question in the exam
	 * 
	 * @return number of question in this exam
	 */
	public int size()
	{
		return questions.size();
	}

	/**
	 * Get the date the exam was created
	 * 
	 * @return Date the exam was created
	 */
	public String dateCreated()
	{
		return dateFormat.format(date_created);
	}

	/**
	 * Get the date the exam is held
	 * 
	 * @return The date the exam was given
	 */
	public String dateScheduled()
	{
		return dateFormat.format(date_scheduled);
	}

	/*
	 * Below are the Iterator functions
	 */
	/**
	 * Return to the beginning of question list
	 */
	public void reset()
	{
		previousQuestion = -1;
	}

	/**
	 * Check if there is another question in the list
	 */
	public boolean hasNext()
	{
		if (previousQuestion + 1 < questions.size())
			return true;
		return false;
	}

	/**
	 * Return the next Question in the list
	 */
	public Question next()
	{
		return questions.get(++previousQuestion);
	}
	
	/**
	 * Remove a question from the list. NOT IMPLEMENTED
	 */
	public void remove()
	{
	}

}
